import { deleteNews, fetchNewsList, createNews, updateNews,queryTagList } from '@/services/ant-design-pro/news';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import { FooterToolbar, PageContainer, ProDescriptions, ProTable } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Button, Drawer, Form, Input, message, Popconfirm, Switch,Image, DatePicker, Select, Tag } from 'antd';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import RichTextEditor from '@/components/RichTextEditor';
import ImageUpload from '@/components/ImageUpload';
import moment from 'moment';
const NewsList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.NewsItem | undefined>();
  const [isEditMode, setIsEditMode] = useState<boolean>(false); // 判断是编辑还是新增
  const [selectedRowsState, setSelectedRows] = useState<API.NewsItem[]>([]);
  const [form] = Form.useForm();
  const [loadingStates, setLoadingStates] = useState<{ [key: number]: boolean }>({});
  const [messageApi, contextHolder] = message.useMessage();
  const [options, setOptions] = useState<{ label: string; value: string }[]>([]);
  const [loading, setLoading] = useState(false);
  const [activeKey, setActiveKey] = useState<string>('1');
    // 加载标签数据
    useEffect(() => {
      const fetchTagList = async () => {
        setLoading(true);
        try {
          const result = await queryTagList(); // 调用接口
          setOptions(result); // 设置 options
        } catch (error) {
          console.error('加载标签列表失败:', error);
        } finally {
          setLoading(false);
        }
      };
  
      fetchTagList();
    }, []);

  const { run: delRun, loading: deleteLoading } = useRequest(deleteNews, {
    manual: true,
    onSuccess: () => {
      setSelectedRows([]);
      actionRef.current?.reloadAndRest?.();
      messageApi.success('删除成功');
    },
    onError: () => {
      messageApi.error('删除错误');
    },
  });
  const handleToggleEnable = async (id: number, enabled: boolean) => {
    try {
      setSelectedRows((prev) =>
        prev.map((row) =>
          row.id === id ? { ...row, prRecommend: enabled ? '1' : '0' } : row
        )
      );
      setLoadingStates((prev) => ({ ...prev, [id]: true }));
      await updateNews({ id, prRecommend: enabled ? 1 : 0 });
      actionRef.current?.reload();
      message.success(enabled ? '推荐成功' : '取消成功');
    } catch (error) {
      message.error(enabled ? '推荐失败' : '取消失败');
    }finally {
      setLoadingStates((prev) => ({ ...prev, [id]: false }));
    }
  };
  const handleSave = useCallback(
    async (values: API.NewsItem) => {
      values.indexStatus = values.indexStatus ? 1 : 0;
      values.createTime = values.createTime.format('YYYY-MM-DD HH:mm:ss')
      if (isEditMode) {
        await updateNews({ ...currentRow, ...values });
        messageApi.success('更新成功');
      } else {
        await createNews(values);
        messageApi.success('添加成功');
      }
      setDrawerVisible(false);
      actionRef.current?.reload();
    },
    [isEditMode, currentRow, actionRef],
  );
  
  const handleEdit = (record: API.NewsItem) => {
    const formattedRecord = {
      ...record,
      indexStatus: record.indexStatus === 1 ? true : false,
      tagIdList:record.tagList.map((item)=>{
        return item.id
      }),
      releaseTime: record.releaseTime ? moment(record.releaseTime, 'YYYY-MM-DD HH:mm:ss') : null,
    };
    console.log(record,'---record')
    setCurrentRow(record);
    setIsEditMode(true);
    form.setFieldsValue(formattedRecord);
    setDrawerVisible(true);
  };

  const columns: ProColumns<API.NewsItem>[] = [
    {
      title: '标题',
      dataIndex: 'title',
      render: (text, record) => (
        <a onClick={() => {

          setCurrentRow(record);
          setIsEditMode(true);
          form.setFieldsValue(record);
          setDrawerVisible(true);

        }}>{text}</a>
    )},
    {
      title: '标签',
      dataIndex: 'tagId',
      valueType: 'select',
      render: (_, record) => (
        <div>
          {record.tagList.map((tag) => (
            <Tag  key={tag.id} style={{ marginRight: 8 }}>
              {tag.name}
            </Tag >
          ))}
        </div>
      ),
      renderFormItem: () => (
        <Select
          // mode="multiple"
          allowClear
          options={options}
        />
      )
    },
    
    {
      title: '图片',
      dataIndex: 'picture',
      search: false,
      render: (text) => <Image src={text} alt="图片"  width={100} height={40} />,
    
    },
    {
      title:'推荐',
      dataIndex: 'recommend',
      valueType: 'switch',
      search: false,
      valueEnum: {
        0: { text: '' },
        1: { text: '推荐' },
      },
      render: (_, record) => (
        <Switch
        loading={loadingStates[record.id] || false}
        checked={record.prRecommend === '1'}
        onChange={(checked) => handleToggleEnable(record.id, checked)}
      />)
    },
    {
      width:120,
      title: '发布时间',
      dataIndex: 'releaseTime',
      valueType: 'dateTime',
      ellipsis:true,
      search: false,
      renderText: (val: string) => `${val}`,
    },
    {
      width:120,
      title: '更新时间',
      dataIndex: 'updateTime',
      ellipsis: true,
      valueType: 'dateTime',
      search: false,
      renderText: (val: string) => `${val}`,
    },
    {
      title:'排序',
      dataIndex: 'sort',
      search:false
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 80,
      align: 'center',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => handleEdit(record)}
        >
          编辑
        </a>,
        <Popconfirm
          key="delete"
          title="确定删除该新闻吗？"
          onConfirm={() => handleRemove([record])}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const handleRemove = useCallback(
    async (selectedRows: API.NewsItem[]) => {
      if (!selectedRows?.length) {
        messageApi.warning('请选择删除项');
        return;
      }
      await delRun({
        params: {
          id: selectedRows.map((row) => row.id).join(','),
        },
      });
    },
    [delRun],
  );

  return (
    <PageContainer  header={{
      title: '', // 设置标题为空字符串
    }}>
      {contextHolder}
      <ProTable<API.NewsItem, API.PageParams>
        headerTitle="新闻列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        toolBarRender={() => [
          <Button
            key={'button'}
            type="primary"
            onClick={() => {
              setCurrentRow(undefined);
              setIsEditMode(false);
              form.resetFields();
              setDrawerVisible(true);
            }}
          >
            新建新闻
          </Button>,
        ]}
        request={(params)=>fetchNewsList({...params,type:activeKey})}
        columns={columns}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activeKey,
            items: [
              { key: "1", label: <span>新闻</span> },
              { key: "2", label: <span>行业</span> },
             
            ],
            onChange: (key) => {
              setActiveKey(key as string);
              actionRef.current?.reloadAndRest();
            },
          },
        }}
        
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选中 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项
            </div>
          }
        >
          <Button
            loading={deleteLoading}
            onClick={() => {
              handleRemove(selectedRowsState);
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}

      <Drawer
        title={isEditMode ? '编辑新闻' : '新建新闻'}
        width={1000}
        open={drawerVisible}
        onClose={() => {
          setDrawerVisible(false);
        }}
        closable={false}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
          initialValues={currentRow || {}}
        >
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入新闻标题' }]}
          >
            <Input placeholder="请输入新闻标题" />
          </Form.Item>
          
          <Form.Item
            name="info"
            label="简介"
            rules={[{ required: true, message: '请输入新闻简介' }]}
          >
            <Input placeholder="请输入新闻简介" />
          </Form.Item>
          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: '请输入新闻内容' }]}
          >
            <RichTextEditor
              value={form.getFieldValue('content')}
              onChange={(value) => form.setFieldsValue({ content: value })}
            />
          </Form.Item>
          <Form.Item name="picture" label="上传图片" rules={[{ required: true, message: '请上传图片' }]}>
            <ImageUpload maxHeight={254} maxWidth={356} value={form.getFieldValue('picture')} onChange={(url) => form.setFieldsValue({ picture: url })} />
          </Form.Item>
           {/* 分类 */}
           <Form.Item name="type" label="分类" rules={[{ required: true, message: '请选择分类' }]}>
            <Select
              placeholder="请选择分类"
              // defaultValue={currentRow?.categoryId}
              style={{ width: '100%' }}
              defaultValue={ + activeKey}
              options={[
                { value: 1, label: '新闻' },
                { value: 2, label: '行业' },
              ]}
            />
           </Form.Item>
           <Form.Item name="tagIdList" label="标签" >
           <Select
              mode="multiple"
              placeholder="请选择标签"
              // defaultValue={[...currentRow?.tagIdList]}
              style={{ width: '100%' }}
              options={  options}
            />
          </Form.Item>
          <Form.Item name="indexStatus" label="推荐到首页" >
            <Switch />
          </Form.Item>
          <Form.Item
            name="releaseTime"
            label="发布时间"
            rules={[{ required: true, message: '请选择发布时间' }]}
          >
            <DatePicker showTime />
          </Form.Item>
          <Form.Item
            name="seoTitle"
            label="seo标题"
          >
            <Input placeholder="请输入seo标题" />
          </Form.Item>
          <Form.Item
            name="seoKeys"
            label="seo关键词"
          >
            <Input placeholder="请输入seo关键词 " />
          </Form.Item>
          <Form.Item
            name="seoDesc"
            label="seo描述"
          >
            <Input.TextArea placeholder="请输入seo描述" />
          </Form.Item>

          <Form.Item
            name="sort"
            label="排序"
          >
            <Input placeholder="请输入排序" type='number' value={0}/>
          </Form.Item>
   
          <Form.Item>
            <Button type="primary" htmlType="submit">
              {isEditMode ? '更新' : '创建'}
            </Button>
            <Button
              style={{ marginLeft: 8 }}
              onClick={() => setDrawerVisible(false)}
            >
              取消
            </Button>
          </Form.Item>
         
        </Form>
      </Drawer>

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.title && (
          <ProDescriptions<API.NewsItem>
            column={2}
            title={currentRow?.title}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.title,
            }}
            columns={columns as ProDescriptionsItemProps<API.NewsItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default NewsList;